<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="60%">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <!-- 第一行：车辆名称、维修地点 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="车辆名称" prop="vehicleName">
            <el-select v-model="formData.vehicleName" placeholder="请选择" filterable>
              <el-option
                v-for="vehicle in vehicleList"
                :key="vehicle.id"
                :label="vehicle.vehicleName"
                :value="vehicle.vehicleName"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="经手人" prop="nickName">
            <UserSelect @node-change="handleNodeChange" v-model="formData.nickName"  />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第二行：维修日期、维修费用 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="费用日期" prop="expenseDate">
            <el-date-picker
              v-model="formData.expenseDate"
              type="date"
              value-format="x"
              placeholder="请选择费用日期"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="费用金额" prop="expenseAmount">
            <el-input v-model="formData.expenseAmount" placeholder="费用金额" />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第三行：相关附件、经手人 -->
      <!-- <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="相关附件">
            <el-upload
              action="#"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :file-list="formData.attachments"
              multiple
            >
              <el-button type="primary">点击上传</el-button>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row> -->

      <!-- 第四行：维修内容 -->
      <el-form-item label="费用主题" prop="expenseSubject">
        <!--        <Editor v-model="formData.repairContent" height="150px" />-->
        <el-input
          v-model="formData.expenseSubject"
          style="width: 100%;"
          :rows="4"
          type="textarea"
          placeholder="请输入维修内容"
        />
      </el-form-item>
       <!-- 相关附件 -->
      <el-col :span="24">
        <el-form-item label="相关附件">
          <OaFileManager :folderDisabled="true"  :initial-file-ids="formData.files" @fileSelectSuccess="fileSelectScccess" />
        </el-form-item>
      </el-col>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { VehicleExpenseApi, VehicleExpenseVO } from '@/api/oa/vehicleexpense'
import UserSelect from '@/views/system/user/UserSelect.vue'
import { useVehicleList } from '@/hooks/web/useVehicleList'


/** 车辆费用记录 表单 */
defineOptions({ name: 'VehicleExpenseForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  expenseDate: undefined,
  expenseAmount: undefined,
  expenseSubject: undefined,
  vehicleName: undefined,
  licensePlate: undefined as string | undefined,
  handlerId: undefined,
  nickName: undefined,
})
const formRules = reactive({
  expenseDate: [{ required: true, message: '费用日期不能为空', trigger: 'blur' }],
  expenseAmount: [{ required: true, message: '费用金额(元)不能为空', trigger: 'blur' }],
  expenseSubject: [{ required: true, message: '费用主题不能为空', trigger: 'blur' }],
  vehicleName: [{ required: true, message: '车辆名称不能为空', trigger: 'blur' }],
  licensePlate: [{ required: true, message: '车牌号码不能为空', trigger: 'blur' }],
  handlerId: [{ required: true, message: '跟进人不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref

const licensePlateRef = ref<string | undefined>(undefined)
const { vehicleList, loadVehicleList, updateLicensePlate } = useVehicleList()


// 监听车辆名称变化
watch(
  () => formData.value.vehicleName,
  (newVal) => {
    updateLicensePlate(newVal, licensePlateRef)
  }
)


/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await VehicleExpenseApi.getVehicleExpense(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  formData.value.licensePlate = licensePlateRef.value

  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as VehicleExpenseVO
    if (formType.value === 'create') {
      await VehicleExpenseApi.createVehicleExpense(data)
      message.success(t('common.createSuccess'))
    } else {
      await VehicleExpenseApi.updateVehicleExpense(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    expenseDate: undefined,
    expenseAmount: undefined,
    expenseSubject: undefined,
    vehicleName: undefined,
    licensePlate: undefined,
    handlerId: undefined,
    nickName: undefined,
  }
  formRef.value?.resetFields()
}

/** 员工被点击事件 */
const handleNodeChange = async (row) =>{
  formData.value.handlerId = row.id
  formData.value.nickName = row.nickname
}
const fileSelectScccess = (fileIds: string[]) => {
  formData.value.files = fileIds.join(',')
}
onMounted(() => {
  loadVehicleList()
})
</script>
